import Koa from 'koa';
import cors from '@koa/cors';
import helmet from 'koa-helmet';
import bodyParser from 'koa-bodyparser';
import { connectDB } from './config/database';
import { envConfig } from './config/environment';
import { log } from './config/logger';
import { errorHandler } from './middleware/errorHandler';
import { requestLogger } from './middleware/requestLogger';
import router from './routes';
import { initializeSystemAdmin } from './scripts/init';
const app = new Koa();
// 初始化系统
// initializeSystemAdmin();
// 连接数据库
connectDB();
// CORS 配置
app.use(cors({
  origin: envConfig.allowedOrigins[0], // 使用第一个允许的源
  credentials: true
}));

// 请求体解析
app.use(bodyParser({
  enableTypes: ['json', 'form', 'text'],
  formLimit: '10mb',
  jsonLimit: '10mb'
}));
// 安全中间件 // 请求日志
app.use(helmet()).use(requestLogger);
// 错误处理
app.use(errorHandler);
// 路由
app.use(router.routes()).use(router.allowedMethods());

// 404 处理
app.use(async (ctx) => {
  ctx.status = 404;
  ctx.body = {
    error: 'Not Found',
    message: `Route ${ctx.method} ${ctx.path} not found`
  };
});

const PORT = envConfig.port;

app.listen(PORT, () => {
  log.info(`Server running on port ${PORT}`);
  log.info(`Environment: ${process.env.NODE_ENV || 'development'}`);
});

export default app;